<?php

namespace App\Traits;

use Sms;
use App\Library\R;
use Illuminate\Support\Facades\Redis;
use Overtrue\EasySms\Message;

trait Msg
{
    public $codeFomatKey = 'app:sms:code:%s';
    public $lastRequestKey = 'app:sms:code:expires:%s';
    public $wxMiniLoginKey = 'wxmini:login:%s';

    /**
     * 检测手机号码格式
     * @param $phone
     * @return int
     */
    public function verifyPhone($phone)
    {
        return preg_match('/^1[3456789][0-9]{9}$/', $phone);
    }

    /**
     * 发送短信验证码
     * @param $phone
     * @param Message $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendMsg($phone, Message $message)
    {
        if (!$this->verifyPhone($phone)) {
            return R::error('手机号码格式错误');
        }

        return Sms::send($phone, $message);
    }

    /**
     * 验证 短信验证码
     * @param $phone
     * @param $code
     * @return bool
     */
    public function verifyMsgCode($phone, $code)
    {
        $key = sprintf($this->codeFomatKey, $phone);
        return $code == Redis::get($key);
    }

    /**
     * 存储验证码
     * @param $phone
     * @param $code
     * @return bool
     */
    public function storeMsgCode($phone, $code)
    {
        $key = sprintf($this->codeFomatKey, $phone);
        Redis::setex($key, '300', $code); // 有效期 5分钟

        return true;
    }

    /**
     * 记录验证码请求标识
     * @param $phone
     * @return bool
     */
    public function storeLastCodeTime($phone)
    {
        $key = sprintf($this->lastRequestKey, $phone);
        Redis::set($key, time(), 'EX', 60); // 请求频率 60秒/次

        return true;
    }

    /**
     * 获取最后一次请求时间
     * @param $phone
     * @return bool
     */
    public function getLastCodeTime($phone)
    {
        $key = sprintf($this->lastRequestKey, $phone);
        if (Redis::get($key)) {
            return true;
        }

        return false;
    }

    //验证图形验证码
    public function verifyCaptcha($captcha)
    {
        return captcha_check($captcha);
    }

    /**
     * 记录微信小程序登录信息
     * @param $uuid
     * @param $openid
     * @param $sessinKey
     * @return bool
     */
    public function storeWxMiniLoginKey($uuid, $openid, $sessinKey)
    {
        $key = sprintf($this->wxMiniLoginKey, $uuid);
        Redis::setex($key, '86400', json_encode(compact($openid, $sessinKey))); // 有效期 24小时

        return true;
    }

}